package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.TencentWeiBoDownloader;
import com.spider.silence.utils.XmlUtil;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * @author liyuanguo
 * @version V1.0
 * @time 2017/2/8 10:13
 * @description
 */
public class TencentWeiBoDownLoaderPool {
    private Logger logger = Logger.getLogger(TencentWeiBoDownLoaderPool.class);
    private static  TencentWeiBoDownLoaderPool instance=new TencentWeiBoDownLoaderPool();;
    protected LinkedList<TencentWeiBoDownloader> pool = Lists.newLinkedList();


    private  TencentWeiBoDownLoaderPool(){
        Document document = XmlUtil.getConf("META-INF/Tencent-WeiBo-conf.xml");
        final List<Element> elements=document.getRootElement().element("login-user-list").elements();
        Thread thread =new Thread(new Runnable() {
            @Override
            public void run() {
                List<String[]> list = Lists.newArrayList();
                for(int i=0;i<elements.size();i++){
                    try {
                        Element e = elements.get(i);
                        String qi=e.element("login-id").getText();
                        String pwd=e.element("pwd").getText();
                        String[] info=new String[]{qi,pwd};
                        list.add(info);
                    }  catch (Exception e) {
                        e.printStackTrace();
                        logger.error(e.getMessage(),e);
                    }
                }
                Collections.shuffle(list);//打乱登录顺序
                for(int i=0;i<list.size();i++){
                    String[] info=list.get(i);
                    TencentWeiBoDownloader tencentWeiBoDownloader= null;
                   /* HashMap<String,String> headers=new HashMap<String, String>();
                    headers.put("Cache-Control","max-age=0");*/
                   // headers.put("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,**/*//*;q=0.8");
                    /*headers.put("Accept-Encoding","gzip, deflate, sdch");
                    headers.put("Accept-Language","zh-CN,zh;q=0.8");
                    headers.put("Upgrade-Insecure-Requests","1");
                    headers.put("Connection","keep-alive");*/
                    tencentWeiBoDownloader=new TencentWeiBoDownloader(info[0],info[1]);
                    //System.out.println("用户名+密码："+info[0]+":"+info[1]);
                    boolean flag=tencentWeiBoDownloader.init();
                    //System.out.println("登录是否成功:"+flag);
                    if(flag){
                        synchronized (pool){
                            pool.add(tencentWeiBoDownloader);
                            pool.notifyAll();
                        }
                    }
                }
            }
        });
        thread.start();
    }


    public  static TencentWeiBoDownLoaderPool getInstance(){
        return  instance;
    }
    public  void releaseDownLoader(TencentWeiBoDownloader downloader) {
        if (downloader != null) {
            synchronized (pool) {
                pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }


    public  TencentWeiBoDownloader fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            if(mills<=0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else {
                long future= System.currentTimeMillis()+mills;
                long remianing=mills;
                while (pool.isEmpty() && remianing >0){
                    pool.wait(remianing);
                    remianing=future-System.currentTimeMillis();
                }
                TencentWeiBoDownloader downLoader =null;
                if(!pool.isEmpty()){
                    downLoader=pool.removeFirst();
                }
                return downLoader;
            }
        }
    }


    public  TencentWeiBoDownloader fetchDownLoader() throws InterruptedException {
        synchronized (pool){
            while (pool.isEmpty()){
                pool.wait();
            }
            return pool.removeFirst();
        }
    }


    public void empty(){
        pool=Lists.newLinkedList();
    }
}
